/**
 * 
 */
package urban;

import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

/**
 * @author emily
 * 
 */
public abstract class StringObject extends PersistsImpl implements Runnable {

	private URL url;
	private String htmlCode;

	public boolean populate(String link) throws XMLStreamException {
		StringBuilder builder;
		Scanner reader;

		try {
			this.url = new URL(link);
			reader = new Scanner(url.openStream());
			builder = new StringBuilder();
			htmlCode = "";

			while (reader.hasNext()) {
				builder.append(reader.nextLine() + "\n");
			}
			htmlCode = builder.toString();

			if (htmlCode
					.contains("MobileDetector.redirect(navigator.userAgent, document.cookie, \"/iphone\");")
					|| htmlCode
							.contains("error_messages = ['oops, my bad', 'aw fiddlesticks', 'gosh darn', 'dammit', 'aw fudge', 'omgwtf', 'wtf', 'bugger', 'crikey', 'drat', 'my bad', 'lame', 'phooey', 'aw snap', 'doh! we f\'d up', 'what the deuce?', 'double turds', 'that sucks'];")
					|| htmlCode
							.contains("</i> isn't defined <a href=\"/add.php?word=")
					|| htmlCode.contains("\">yet</a>, but these are close:"))
				return false;
			reader.close();
		} catch (MalformedURLException e) {

			System.out.println(link + " is a bad url link");
			return false;

		} catch (IOException e) {

			System.out.println("Could not open link: " + link);
			return false;

		}
		parseHTML();
		return true;
	}

	public void parseHTML() throws XMLStreamException {

		StringReader s = new StringReader(htmlCode);
		XMLStreamReader xmlStreamReader = null;
		try {
			xmlStreamReader = XMLInputFactory.newInstance()
					.createXMLStreamReader(s);
		} catch (XMLStreamException e) {
			System.out.println("Bad HTML Code");
		} catch (FactoryConfigurationError e) {
			System.out.println("Error with Factory Configuration");
		}

		while (xmlStreamReader.hasNext()) {
			fillEventInfo(xmlStreamReader);
		}
		xmlStreamReader.close();
		s.close();
	}

	abstract void fillEventInfo(XMLStreamReader reader)
			throws XMLStreamException;

	public abstract String toString();

}
